<template>
	<view class="page-container">
		<!-- 导航栏：通过 safeArea 适配刘海屏，通过 showup 控制显示/隐藏 -->
		<shopNavbar :top="navBarTop" :showup="showup" :pageTitle="shopName" @handleBack="handleNavBack" :isAdmin="isAdmin"></shopNavbar>
		<view class="popupbox" v-if="popshow" @touchend.prevent="maskClick">
			<view class="popupview">
				<view class="popup-item" v-for="(value, index) in userList" :key="index" @touchend.prevent="navigateToMerchantDetail(value.userId)">
					<view class="merchant-avatar">
						<image :src="value.nicPic.url" mode="aspectFill" class="avatar-img"></image>
					</view>
					<text class="merchant-name">{{ value.nicName }}</text>
				</view>
			</view>
		</view>

		<!-- 主内容区：通过 scroll 事件控制导航栏，移除外层 touch 事件避免冲突 -->
		<scroll-view class="content" scroll-y enhanced show-scrollbar="false" @scroll="handleScroll" :style="{ paddingTop: navBarTop + navBarHeight + 8 + 'rpx' }">
			<!-- 商家列表区域 -->
			<view class="merchant-section">
				<uni-segmented-control :current="current" :values="items" @clickItem="onClickItem" styleType="text" activeColor="#55aaff"></uni-segmented-control>
				<view class="content">
					<view v-show="current === 0" class="">
						<!-- 横向滑动商家列表：固定高度避免滚动失效 -->
						<view class="sellerHead">
							<scroll-view class="merchant-scroll" scroll-x enhanced show-scrollbar="false">
								<view class="merchant-list">
									<view class="merchant-item" v-for="(value, index) in userList" :key="index" @click="navigateToMerchantDetail(value.userId)">
										<view class="merchant-avatar">
											<image :src="value.nicPic.url" mode="aspectFill" class="avatar-img"></image>
										</view>
										<text class="merchant-name">{{ value.nicName }}</text>
									</view>
								</view>
							</scroll-view>
							<view class="section-more" @click="navigateToAllMerchants">
								<text class="more-text">查看全部</text>
								<uni-icons type="right" size="16" color="#55aaff"></uni-icons>
							</view>
						</view>
						<view class="product-section">
							<view class="section-header" @click="createProduct">
								<text class="section-title">推荐商品</text>
							</view>

							<!-- 商品网格布局 -->
							<view class="product-container">
								<!-- 	左边栏 -->
								<view class="product-grid">
									<view class="product-card" v-for="(product, index) in productList.left" :key="index">
										<!-- 商品图片 -->
										<shopProductCard :product="product"></shopProductCard>
									</view>
								</view>
								<!-- 右边栏 -->
								<view class="product-grid">
									<view class="product-card" v-for="(product, index) in productList.right" :key="index">
										<shopProductCard :product="product"></shopProductCard>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view v-show="current === 1" class="">
						<shopCategory :productList="products" :userList="userList" :category="category" :senderUserId="senderUserId"></shopCategory>
					</view>
				</view>
			</view>

			<!-- 商品展示区域 -->
		</scroll-view>
	</view>
</template>

<script>
import shopNavbar from '../../components/shopNavbar.vue';
import shopProductCard from '../../components/shop/shopProductCard/shopProductCard.vue';
import shopCategory from '../../components/shop-category.vue';
const db = uniCloud.databaseForJQL();
export default {
	components: {
		shopProductCard,
		shopNavbar,

		shopCategory
	},
	props: {
		products: {
			type: Array,
			default: () => []
		},
		userList: {
			type: Array,
			default: () => []
		}
	},
	data() {
		return {
			merchants: [],
			shopName: '',
			showup: true, // 导航栏显示/隐藏开关
			navBarTop: 0, // 导航栏顶部安全区域距离（适配刘海屏）
			navBarHeight: 120, // 导航栏高度（需与 shopNavbar 内部高度一致）
			lastScrollTop: 0, // 上一次滚动距离（用于判断滚动方向）
			scrollThreshold: 50, // 触发导航栏隐藏的滚动阈值（rpx）
			popshow: false,
			isAdmin: true,
			current: 0,
			items: ['商家列表', '分类查看'],
			category: [],
			loading: false,
			senderUserId: ''
		};
	},
	computed: {
		productList() {
			const left = [];
			const right = [];
			this.products.forEach((item, index) => {
				if (index % 2 === 0) {
					left.push(item);
				} else {
					right.push(item);
				}
			});
			return { left, right };
		},
		storeData() {
			return this.$store.state.msg;
		}
	},

	mounted() {
		// 1. 获取设备安全区域，适配刘海屏（传给导航栏）
		this.systemInfo();
		this.getCategory();
	},
	methods: {
		onClickItem(e) {
			if (this.current != e.currentIndex) {
				this.current = e.currentIndex;
			}
		},

		systemInfo() {
			try {
				const res = this.$store.state.msg.systemInfo;
				// 转换为 rpx（UniApp 中 1px = 2rpx，需根据设备像素比计算）
				this.navBarTop = res.safeArea.top * (750 / res.windowWidth);
				console.log('安全区', this.navBarTop);
			} catch (e) {
				console.error('获取设备信息失败：', e);
				this.navBarTop = 0;
			}

			this.lastScrollTop = 0;
		},
		maskClick() {
			this.popshow = false;
		},
		async getCategory() {
			try {
				this.loading = true;

				// 1. 安全获取 userId
				const globalState = this.$store.state || {};
				const userInfo = globalState.msg?.user || {};
				const userUserId = userInfo.userId; // 用户自己的 userId
				const defaultUserId = 'system'; // 默认的 userId

				let finalResult = []; // 用于存储最终查询结果

				// 2. 第一步：使用用户自己的 userId 进行查询
				if (userUserId) {
					console.log(`正在使用用户 userId ${userUserId} 查询分类...`);
					const userRes = await db.collection('category').where({ userId: userUserId }).get();

					// 检查查询结果是否有效且不为空
					if (userRes && Array.isArray(userRes.data) && userRes.data.length > 0) {
						finalResult = userRes.data;
						
					} else {
						console.warn(`用户 userId ${userUserId} 未查询到分类数据，将使用默认 userId ${defaultUserId} 重试...`);
					}
				} else {
					console.warn('未获取到用户 userId，将直接使用默认 userId 查询...');
				}

				// 3. 第二步：如果第一步结果为空，则使用默认 userId 进行查询
				if (finalResult.length === 0) {
				
					const defaultRes = await db.collection('category').where({ userId: defaultUserId }).get();

					if (defaultRes && Array.isArray(defaultRes.data)) {
						finalResult = defaultRes.data;
					
					} else {
						console.warn(`默认 userId ${defaultUserId} 也未查询到分类数据。`);
					}
				}

				// 4. 处理最终结果并赋值
				if (finalResult.length > 0) {
					this.category = finalResult[0].category;
					
				} else {
					this.category = []; // 如果两次查询都为空，也给一个空数组兜底
				}
			} catch (e) {
				// 5. 错误处理
				console.error('获取分类失败：', {
					error: e,
					userId: this.$store.state?.msg?.user?.userId
				});
				this.category = [];
			} finally {
				// 6. 确保加载状态关闭
				this.loading = false;
			}
		},
		// 处理 scroll-view 滚动：控制导航栏显示/隐藏
		handleScroll(e) {
			const currentScrollTop = e.detail.scrollTop; // 当前滚动距离（px）
			// 转换为 rpx（统一单位计算）
			const currentScrollTopRpx = currentScrollTop * (750 / this.$store.state.msg.systemInfo.windowWidth);

			// 逻辑：向上滚动（current > last）且超过阈值 → 隐藏导航栏；向下滚动 → 显示
			if (currentScrollTopRpx - this.lastScrollTop > 10) {
				// 向上滚动：超过阈值隐藏
				if (currentScrollTopRpx > this.scrollThreshold) {
					this.showup = false;
					this.navBarHeight = 90;
				}
			} else if (this.lastScrollTop - currentScrollTopRpx > 10) {
				// 向下滚动：显示导航栏
				this.showup = true;
				this.navBarHeight = 120;
			}

			this.lastScrollTop = currentScrollTopRpx;
		},

		// 导航栏返回按钮事件（接收子组件传参）
		handleNavBack() {
			uni.navigateBack({ delta: 1 });
		},

		// 导航到商家详情页（修复路径，携带商家ID）
		navigateToMerchantDetail(merchantId) {
			this.$emit('shopDetail', merchantId);
		},

		// 导航到所有商家页面
		navigateToAllMerchants() {
			this.popshow = !this.popshow;
		},

		// 跳转创建商品页面
		createProduct() {
			uni.navigateTo({
				url: '/pages/createProduct/createProduct'
			});
		},

		async fetchProducts() {
			try {
				const res = await uni.request({ url: '/api/products', method: 'GET' });
				this.products = res.data || [];
			} catch (error) {
				console.error('获取商品数据失败：', error);
			}
		}
	}
};
</script>

<style lang="scss" scoped>
/* 页面容器：消除页面级滚动，仅保留 scroll-view 滚动 */
.page-container {
	position: relative;
	min-height: 100vh;
	background-color: #f5f5f5;
	overflow: hidden; /* 防止页面级滚动 */
}

/* 主内容区：动态计算高度，确保滚动空间 */
.content {
	width: 100%;
	/* 高度 = 视口高度 - 导航栏高度 - 底部栏高度（底部栏假设 120rpx） */
	height: calc(100vh - #{60rpx} - #{60rpx});
	box-sizing: border-box;
	margin-top: 30rpx;
}

/* 商家列表区域 */
.merchant-section {
	background-color: #fff;
	margin-bottom: 10rpx;
	padding: 0rpx 20rpx;
}
.sellerHead {
	position: relative;
	display: flex;
}
/* 横向商家滚动容器：固定高度，确保横向滚动正常 */
.merchant-scroll {
	padding: 0 12rpx;
	height: 180rpx; /* 固定高度 = 商家头像 120rpx + 文字 30rpx + 间距 30rpx */
	white-space: nowrap; /* 防止子元素换行 */
}

.merchant-list {
	display: inline-flex; /* 横向排列且不换行 */
	gap: 12rpx;
}

.merchant-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	width: 120rpx;
}
.popupbox {
	position: fixed;
	display: flex;
	top: 0;
	left: 0;
	right: 0;
	padding: 20rpx 30rpx;
	bottom: 0;
	z-index: 9999;
	background-color: rgba(0, 0, 0, 0.3);
}
.popupview {
	display: flex;
	border-radius: 20rpx;
	background-color: #fff;
	width: 100%;
	margin-top: 300rpx;
	margin-bottom: auto;
}
.popup-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	margin: 10rpx 10rpx;
}
.merchant-avatar {
	width: 120rpx;
	height: 120rpx;
	border-radius: 50%;
	overflow: hidden;
	margin-bottom: 12rpx;
	border: 2rpx solid transparent;
	transition: all 0.3s ease;

	&:active {
		transform: scale(0.95);
	}
}

.merchant-item:first-child .merchant-avatar {
	border-color: rgba(255, 61, 0, 0.3);
	transition: all 0.3s ease;
	&:active {
		transform: scale(0.9);
	}
}

.avatar-img {
	width: 100%;
	height: 100%;
	object-fit: cover; /* 防止图片拉伸 */
}

.merchant-name {
	font-size: 26rpx;
	color: #333;
	text-align: center;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
	width: 100%;
}
.product-container {
	display: flex;
	padding: 10rpx 20rpx;
	gap: 20rpx; /* 两列之间的间距 */
	width: 100%;
	box-sizing: border-box;
}
/* 商品列表区域 */
.product-section {
	background-color: #fff;
	padding-bottom: 24rpx;
	padding: 10rpx 20rpx;
}

/* 通用区域标题 */
.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 24rpx 24rpx 16rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.section-more {
	position: absolute;
	right: 20rpx;
	width: 28rpx;
	display: flex;
	align-items: center;
}

.more-text {
	font-size: 26rpx;
	color: #55aaff;
	margin-right: 6rpx;
}

/* 商品网格布局 */
.product-grid {
	width: calc(50% - 10rpx); /* 50%宽度 - 10rpx（间距的一半），确保总宽度不溢出 */
	display: flex;
	flex-direction: column;
	gap: 25rpx; /* 列内商家卡片的上下间距 */
}

.product-card {
	background-color: #fff;
	border-radius: 16rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	transition: all 0.3s ease;

	&:active {
		transform: scale(0.98);
	}
}
</style>